import {
  getSearchHot,
  getSearchSuggest,
  getSearchResult
} from '../../services/search'
import stringToNodes from '../../utils/string2nodes'
import debounce from '../../utils/debounce'
const debounceGetSearchSuggest = debounce(getSearchSuggest, 300)
Page({
  data: {
    searchValue: "",
    hotkeyWords: [],
    suggestSongs: [],
    suggestSongsNodes: [],
    resultSongs:[],

  },
  onLoad() {
    this.getPageData()
  },
  // 网络请求
  getPageData() {
    getSearchHot().then(res => {
      this.setData({ hotkeyWords: res.result.hots })
    })
  },


  // 事件处理
  handleSearchChange(event) {
    // 1.获取输入的关键字
    const searchValue = event.detail
    // 2.保存
    this.setData({
      searchValue
    })
    // 3.判断为空 处理逻辑
    if (!searchValue.length) {
      this.setData({suggestSongs: [],resultSongs: [] })
      debounceGetSearchSuggest.cancel()
      return
    }

    // 4.根据关键字搜索   防抖
    debounceGetSearchSuggest(searchValue).then(res => {
        this.setData({
          suggestSongs: res.result.allMatch
        })
      // 1.获取建议的关键字歌曲
      const suggestSongs = res.result.allMatch
      this.setData({
        suggestSongs
      })
      if (!suggestSongs) return
      // 2.转成nodes节点
      const suggestKeywords = suggestSongs.map(item => item.keyword)
      const suggestSongsNodes = []
      for (const keyword of suggestKeywords) {
        const nodes = stringToNodes(keyword, searchValue)
        suggestSongsNodes.push(nodes)
      }
      this.setData({
        suggestSongsNodes
      })
    })
  },
  
  // 保存一下searchValue
  handleSearchAction(){
    const searchValue = this.data.searchValue
    getSearchResult(searchValue).then((res)=>{
      this.setData({
        resultSongs:res.result.songs
      })
    })
  },


  // 点击发送
  handleKeywordItemTap(event){
    const keyword = event.currentTarget.dataset.keyword
    this.setData({searchValue:keyword})
     // 调用函数 发送请求
    this.handleSearchAction()
  },
  
  onShareAppMessage() {
    return {
      title: 'Time Music',
      path: '/pages/main-music/main-music',
      imageUrl:''
    }
  },
})